<?php
/**
 * 旅游管理
 * User: lxq
 * Date: 2018/3/21
 * Time: 15:27
 */
defined('InNcPHP') or exit('Access Invalid!');
class itineraryControl extends SystemControl{

    private $links = array(
        array('url'=>'act=itinerary&op=index','lang'=>'nc_manage'),
        array('url'=>'act=itinerary&op=add','lang'=>'nc_new'),
    );


    public function __construct()
    {
        parent::__construct();
        Language::read('ticket');
        Tpl::setDir('itinerary');
    }

    /**
     * 路线列表
     */
    public function indexOp()
    {
        $itinerary_model = Model('itinerary');
        $merchant_model = Model('member_merchant');
        //查询条件
        $condition =array();
        $category_model = Model('ticket_category');
        $cates = $category_model->getCategoryList();
        if(isset($_GET['search_title']) && $_GET['search_title']){
            $condition['ir_title'] = array('like','%'.$_GET['search_title'].'%');
        }
        if (isset($_GET['search_state']) && is_numeric($_GET['search_state'])) {
            $condition['ir_status'] = intval($_GET['search_state']);
        }
        $merchant_id = intval($this->admin_info['merchant_id']);
        if($merchant_id>0){
            $condition['merchant_id'] = $merchant_id;
        }else{
            if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
                $condition['merchant_id'] = intval($_GET['search_merchant']);
            }
        }
        if (isset($_GET['search_cate1']) && is_numeric($_GET['search_cate1'])) {
            $condition['cate_id'] = intval($_GET['search_cate1']);
        }

        $day = getgpc('day');
        if($day=='today'){
            $time_from = $time_to = strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d"),date("Y")))) ;
            $time_to = $time_to + 86400;
            $condition['ir_add_time'] = array('between',array($time_from,$time_to));
        }


        $itinerarys = $itinerary_model->getItineraryListPage($condition, '*', 10);
        if($itinerarys){
            foreach ($itinerarys as $k => $ticket) {
                $itinerarys[$k]['shop_name'] = $merchant_model->getfby_merchant_id($ticket['merchant_id'], 'mc_shop_name');
                //$itinerarys[$k]['hotel_thumb'] = UPLOAD . 'itinerary/' . $ticket['ir_thumb'];
                $itinerarys[$k]['hotel_thumb'] = get_thumb($ticket['ir_thumb'],ITINERARY_MARK,240);
                foreach ($cates as $cate) {
                    if ($ticket['cate_id'] == $cate['tc_id']) {
                        $itinerarys[$k]['cate_id'] = $cate['tc_name'];
                    } else if ($ticket['tk_cate2'] == $cate['tc_id']) {
                        $itinerarys[$k]['tk_cate2'] = $cate['tc_name'];
                    }
                }
            }
        }
        $cate1 = $category_model->getCategoryList(array('tc_pid'=>ITINERARY_MARK,'is_del'=>0));//旅行社底下所有分类

        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
        Tpl::output('cate1', $cate1);
        Tpl::output('search', $_GET);
        Tpl::output('merchants',$merchants);
        Tpl::output('itinerarys',$itinerarys);
        Tpl::output('page', $itinerary_model->showpage());
        Tpl::output('top_link',$this->sublink($this->links,'index'));
        Tpl::showpage('itinerary.index');
    }

    /**
     * 添加线路
     */
    public function addOp()
    {
        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        $ticket_category = Model('ticket_category');
        $area_model = Model('area');
        if(chksubmit()){
            $itinerary_model = Model('itinerary');
            $insert_array = array();
            $insert_array['ir_title'] = trim($_POST['title']);
            $insert_array['merchant_id'] = intval($this->admin_info['merchant_id'])>0?intval($this->admin_info['merchant_id']):intval($_POST['merchant_id']);
            $insert_array['ir_market_price'] = floatval($_POST['show_price']);
            $insert_array['price'] = floatval($_POST['price']);
            $insert_array['cate_id'] = intval($_POST['cate1']);
            $insert_array['ir_province_id'] = $_POST['province_id'];
            $insert_array['ir_addr'] = $_POST['addr'];
            $insert_array['cost_price'] = floatval($_POST['cost_price']);
            $insert_array['tel'] = $_POST['hotel_tel'];
            $insert_array['ir_city_name'] = $area_model->getfby_area_id($_POST['city_id'],'name');
            $insert_array['ir_city_id'] = $_POST['city_id'];
            $insert_array['ir_area_id'] = $_POST['area_id'];
            $insert_array['stock']     = $_POST['stock'];
            $insert_array['sales']     = $_POST['sales'];
            $insert_array['ir_detail'] = $_POST['content'];
            $insert_array['ir_tips']   = $_POST['content1'];
            $insert_array['label'] = $_POST['label'];
            $insert_array['is_purchase'] = $_POST['is_purchase'];//是否可以购买
            $insert_array['ir_add_time'] = time();
            $insert_array['ir_update_time'] = time();
            $store_location = trim($_POST['store_location']);
            $store_gps = explode(',', $store_location);
            $insert_array['ir_lat']  = $store_gps[1];//纬度
            $insert_array['ir_lng']  = $store_gps[0];//经度
            $insert_array['ir_full_addr']        = implode('',array(
                $area_model->getfby_area_id(intval($_POST['province_id']),'name'),
                $insert_array['ir_city_name'],
                $area_model->getfby_area_id(intval($_POST['area_id']),'name'),
                $_POST['addr']
            ));
            $upload = new UploadFile();
            $upload->set('default_dir','itinerary/'.$upload->getSysSetPath());
            $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
            $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
            $upload->set('thumb_ext', GOODS_IMAGES_EXT);
            $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
            //封面图片
            $result = $upload->upfile('thumb');
            if($result){
                $insert_array['ir_thumb'] = $upload->getSysSetPath() . $upload->file_name;
            } else {
                //图片上传失败
                $this->log('旅游线路封面图上传失败'.'[标题:'.$_POST['title'].']',0);
                showMessage(L('nc_common_save_fail').$upload->error);
            }
            $result = $itinerary_model->addItinerary($insert_array);
            if($result){
                $url = array(
                    array(
                        'url' => 'index.php?act=itinerary&op=photo&id='.$result,
                        'msg' => '上传图片'
                    ),
                );
                $this->log('添加旅游线路成功'.'[标题:'.$_POST['title'].']',1);
                showMessage(L('nc_common_save_succ'),$url);
            }else{
                showMessage(L('nc_common_save_fail'));
            }

        }
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
        $area_model = Model('area');
        $provinces = $area_model->getAreaList(array('parent_id'=>1));
        $cate = $ticket_category->getCategoryList(array('tc_pid'=>4,'is_del'=>0));//获取旅行社分类
        Tpl::output('provinces',$provinces);
        Tpl::output('top_link',$this->sublink($this->links,'add'));
        Tpl::output('cate',$cate);
        Tpl::output('merchants',$merchants);
        Tpl::showpage('itinerary.add');
    }

    /**
     * 编辑线路
     */
    public function editOp()
    {
        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        $ticket_category = Model('ticket_category');
        $itinerary_model = Model('itinerary');
        $area_model = Model('area');
        $id = intval($_GET['id']);
        if(chksubmit()){
            $itinerary_model = Model('itinerary');
            $insert_array = array();
            $insert_array['ir_title'] = trim($_POST['title']);
            $insert_array['merchant_id'] = intval($this->admin_info['merchant_id'])>0?intval($this->admin_info['merchant_id']):intval($_POST['merchant_id']);
            $insert_array['ir_market_price'] = floatval($_POST['show_price']);
            $insert_array['cost_price'] =floatval( $_POST['cost_price']);
            $insert_array['price'] = floatval($_POST['price']);
            $insert_array['cate_id'] = intval($_POST['cate1']);
            $insert_array['ir_province_id'] = $_POST['province_id'];
            $insert_array['ir_addr'] = $_POST['addr'];
            $insert_array['tel'] = $_POST['hotel_tel'];
            $insert_array['ir_city_name'] = $area_model->getfby_area_id($_POST['city_id'],'name');
            $insert_array['ir_city_id'] = $_POST['city_id'];
            $insert_array['ir_area_id'] = $_POST['area_id'];
            $insert_array['stock']     = $_POST['stock'];
            $insert_array['sales']     = $_POST['sales'];
            $insert_array['ir_detail'] = $_POST['content'];
            $insert_array['ir_tips']   = $_POST['content1'];
            $insert_array['is_purchase'] = $_POST['is_purchase'];//是否可以购买
            $insert_array['label'] = $_POST['label'];
            $insert_array['ir_update_time'] = time();
            $store_location = trim($_POST['store_location']);
            $store_gps = explode(',', $store_location);
            $insert_array['ir_lat']  = $store_gps[1];//纬度
            $insert_array['ir_lng']  = $store_gps[0];//经度
            $insert_array['ir_full_addr']        = implode('',array(
                $area_model->getfby_area_id(intval($_POST['province_id']),'name'),
                $insert_array['ir_city_name'],
                $area_model->getfby_area_id(intval($_POST['area_id']),'name'),
                $_POST['addr']
            ));
           if($_FILES['thumb']['tmp_name']){
                $upload = new UploadFile();
                $upload->set('default_dir','itinerary/'.$upload->getSysSetPath());
                $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
                $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
                $upload->set('thumb_ext', GOODS_IMAGES_EXT);
                $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
                //封面图片
                $result = $upload->upfile('thumb');
                if($result){
                    $insert_array['ir_thumb'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log('旅游线路封面图上传失败'.'[标题:'.$_POST['title'].']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            $result = $itinerary_model->updateItinerary(array('id'=>$id),$insert_array);
            if($result){
                $this->log('编辑旅游线路成功'.'[标题:'.$_POST['title'].']',1);
                showMessage(L('nc_common_save_succ'),'index.php?act=itinerary&op=index');
            }else{
                showMessage(L('nc_common_save_fail'));
            }

        }
        $condition = array();
        $condition['id'] = $id;
        $info = $itinerary_model->getItineraryInfo($condition);
        $info['ir_thumb'] = UPLOAD . 'itinerary/' . $info['ir_thumb'];
        //获取已经选中市、县
        $citys = $area_model->getAreaList(array('parent_id'=>$info['ir_province_id']));
        $areas = $area_model->getAreaList(array('parent_id'=>$info['ir_city_id']));
        array_push($this->links, array('url'=>'act=itinerary&op=edit&id=' .$id ,'lang'=>'nc_edit'));
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'is_disable'=>0), 'merchant_id,mc_shop_name');
        }
        $provinces = $area_model->getAreaList(array('parent_id'=>1));
        $cate = $ticket_category->getCategoryList(array('tc_pid'=>ITINERARY_MARK,'is_del'=>0));//获取旅行社分类
        //基础信息,相册
        $sublinks = array(
            array('url'=>'act=itinerary&op=edit&id=' . $id,'lang'=>'ticket_index_baseinfo'),
            array('url'=>'act=itinerary&op=photo&id=' . $id,'lang'=>'index_photo')
        );
        Tpl::output('sub_link',$this->sublink($sublinks,'edit'));
        Tpl::output('cate',$cate);
        Tpl::output('provinces', $provinces);
        Tpl::output('merchants',$merchants);
        Tpl::output('top_link',$this->sublink($this->links,'edit'));
        Tpl::output('itinerary_info',$info);
        Tpl::output('citys', $citys);
        Tpl::output('areas', $areas);
        Tpl::showpage('itinerary_edit');

    }

    /**
     * 线路相册
     */
    public function photoOp()
    {
        $tk_id = intval($_GET['id']);
        /* @var ticket_imagesModel $images_model */
        $images_model = Model('ticket_images');

        if ($_FILES) {
            $upload = new UploadFile();
            $upload->set('default_dir', 'itinerary/' . $upload->getSysSetPath());
            $upload->set('thumb_width', GOODS_IMAGES_WIDTH);
            $upload->set('thumb_height', GOODS_IMAGES_HEIGHT);
            $upload->set('thumb_ext', GOODS_IMAGES_EXT);
            $upload->set('allow_type', array('gif', 'jpg', 'jpeg', 'png'));
            $result = $upload->upfile('file');
            if($result){
                //得到图片上传后的路径
                $path = $upload->getSysSetPath() . $upload->file_name;
                $params = array(
                    'tk_id' => $tk_id,
                    'img_size' => round($_FILES['file']['size'] / 1024),
                    'img_ext' => $upload->ext,
                    'img_path' => $path,
                    'img_addtime' => time(),
                    'type'=>ITINERARY_MARK
                );
                //保存到数据库
                if ($img_id = $images_model->addTicketImage($params)) {
                    $this->log('上传旅游路线图'.'[tk_id:'.$tk_id.'][img_id:'.$img_id.']', 1);
                    exit(json_encode(array(
                        'res' => true,
                        'id' => $img_id,
                        'path' => UPLOAD . 'itinerary/' . $path
                    )));
                }
            }
            $this->log(L('nc_add,ticket_index_photo').'[tk_id:'.$tk_id.']', 0);
            exit(json_encode(array('res'=>false)));
        }

        Tpl::output('tk_id', $tk_id);
        $images = $images_model->getTicketImageList(array('tk_id'=>$tk_id, 'img_deleted'=>0,'type'=>ITINERARY_MARK));
        foreach ($images as $k => $img) {
            $images[$k]['img_path'] = UPLOAD . 'itinerary/' . $img['img_path'];
        }
        Tpl::output('images',$images);

        array_push($this->links, array('url'=>'act=itinerary&op=edit&id=' . $tk_id,'lang'=>'nc_edit'));
        Tpl::output('top_link',$this->sublink($this->links,'edit'));
        //基础信息,相册
        $sublinks = array(
            array('url'=>'act=itinerary&op=edit&id=' . $tk_id,'lang'=>'ticket_index_baseinfo'),
            array('url'=>'act=itinerary&op=photo&id=' . $tk_id,'lang'=>'index_photo')
        );
        Tpl::output('sub_link',$this->sublink($sublinks,'photo'));
        Tpl::showpage('itinerary.photo');
    }

    /**
     * ajax更改上架状态
     */
    public function  ajaxstatusOp()
    {
        /* @var ticketModel $ticket_model */
        $ticket_model = Model('itinerary');

        $type = $_GET['type'];

        switch ($type) {
            case 'change_recommend':
                $tk_id = $_POST['tk_id'];
                $tk = $ticket_model->getItineraryInfo(array('id'=>$tk_id));
                if ($tk) {
                    $recommend = $tk['tk_is_recommend'] ? 0 : 1;
                    $res = $ticket_model->updateHotel(array('id'=>$tk_id), array('tk_is_recommend'=>$recommend));
                    $action = $recommend ? 'ticket_add_recommend' : 'ticket_index_not_recommend';
                    $this->log(L('ticket_index_ticket,'.$action).'[id:'.$tk_id.']', $res?1:0);
                    exit(json_encode(array('res'=>$res, 'new_recommend'=>$recommend)));
                } else {
                    exit(json_encode(array('res'=>false, 'new_recommend'=>'')));
                }
            case 'change_status':
                $tk_id = $_POST['tk_id'];
                $tk = $ticket_model->getItineraryInfo(array('id'=>$tk_id));
                if ($tk) {
                    $status = $tk['ir_status'] ? 0 : 1;
                    $res = $ticket_model->updateItinerary(array('id'=>$tk_id), array('ir_status'=>$status));
                    $action = $status ? 'ticket_index_show' : 'ticket_index_hide';
                    $this->log('旅游线路'.L($action).'[tk_id:'.$tk_id.']', $res?1:0);
                    exit(json_encode(array('res'=>$res, 'new_status'=>$status)));
                } else {
                    exit(json_encode(array('res'=>false, 'new_status'=>'')));
                }
            case 'change_all':
                $ids = $_POST['ids'];
                $status = $_POST['type'] == 'show' ? 1 : 0;
                $condition = array(
                    'id' => array('in', implode(',', $ids))
                );
                $res = $ticket_model->updateItinerary($condition, array('ir_status'=>$status));
                $action = $status ? 'ticket_index_show' : 'ticket_index_hide';
                $this->log('旅游线路'.L($action).'[id:'.implode(',',$ids).']', $res?1:0);
                exit(json_encode(array('res'=>$res)));
        }
    }

    /**
     * 删除旅游线路
     */
    public function del_itineraryOp()
    {
        $ir_id = $_POST['ir_id'];
        if($ir_id>0){
            /* @var itineraryModel $itinerary_model*/
            $itinerary_model = Model('itinerary');
            /* @var specModel $spec_model */
            $spec_model = Model('spec');
            $ht = $itinerary_model->getItineraryInfo(array('id'=>$ir_id));
            if($ht){
                $res = $itinerary_model->deleteItinerary(array('id'=>$ir_id));
                $res_ = $spec_model->deleteSpec(array('goods_id'=>$ir_id,'type'=>ITINERARY_MARK));
                if($res && $res_){
                    exit(json_encode(array('res'=>true, 'msg_'=>'成功')));
                }else{
                    exit(json_encode(array('res'=>false, 'msg_'=>'删除失败')));
                }
            }else{
                exit(json_encode(array('res'=>false, 'msg_'=>'酒店不存在')));
            }
        }
    }


}